package dao

import (
	"errors"
	"log"

	"gitee.com/legend9999/publisher/modle"

	"gitee.com/legend9999/publisher/conf"
	"github.com/jinzhu/gorm"

	// 数据库驱动
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

var (
	DB *Client
)

func init() {
	DB = NewClient(true)
	DB.SingularTable(true)
	DB.AutoMigrate(new(modle.Book), new(modle.BookStatus), new(modle.User))
}

// Client 数据库实例
type Client struct {
	*gorm.DB
}

// NewConn Fetch a db connection from pool
func (c *Client) Conn() *gorm.DB {
	return c.DB.New()
}

// NewClient Create a PostgresSQL client
func NewClient(debug bool) *Client {
	var (
		db  *gorm.DB
		err error
	)
	postgresUrlUrl := conf.SysConf.PostgresUrl()
	if db, err = gorm.Open("postgres", postgresUrlUrl); err != nil {
		log.Panicf("connect db param:%s err:%s", postgresUrlUrl, err)
	}
	//db, err = gorm.Open("mysql", "root:FYNLizhiwei1234@tcp(139.9.139.92:3306)/jd_customer_service?charset=utf8")

	if err != nil {
		log.Panicf("args:%+v err:%s", 1, err)
	}
	db.LogMode(debug)
	db.BlockGlobalUpdate(true)
	maxIdleConnNum := conf.SysConf.PostgresMaxIdleConnNum()
	if maxIdleConnNum > 0 {
		db.DB().SetMaxIdleConns(maxIdleConnNum)
	}
	postgresMaxOpenConnNum := conf.SysConf.PostgresMaxOpenConnNum()
	if postgresMaxOpenConnNum > 0 {
		db.DB().SetMaxOpenConns(postgresMaxOpenConnNum)
	}
	return &Client{db}
}

var NotFoundErr = errors.New("not found record")
var DBErr = errors.New("db error")
